<template>
  <div>
    <v-dialog title="收回押金"
              :show.sync="dialogVisible"
              width="1200px"
              @beforeClose="beforeClose">
      <div class="card-box">
        <el-form ref="editForm"
                 :model="form"
                 size="small"
                 :rules="rules">
          <div class="form-wrap">
            <el-form-item label="合同名称"
                          prop="lessorContractName">
              <el-input disabled
                        v-model="form.lessorContractName"></el-input>
            </el-form-item>
            <el-form-item label="出租方"
                          prop="customerName">
              <el-input disabled
                        v-model="form.customerName"></el-input>
            </el-form-item>
            <!--  <el-form-item label="关联合同编码" >
                            <el-input disabled v-model="contarct.contractCode"></el-input>
                        </el-form-item>-->
            <el-form-item label="收据编码">
              <el-input v-model="form.dataCode"></el-input>
            </el-form-item>
            <!--<el-form-item label="退款批复号" prop="refundBatch">
                            <el-input disabled v-model="form.refundBatch"></el-input>
                        </el-form-item>-->
            <el-form-item label="收款银行"
                          prop="bankName">
              <el-input v-model="form.bankName"
                        placeholder="请输入收款银行"></el-input>
            </el-form-item>
            <el-form-item label="银行账号"
                          prop="bankAccount">
              <el-input v-model="form.bankAccount"
                        placeholder="请输入银行账号"></el-input>
            </el-form-item>
            <el-form-item label="收款人姓名"
                          prop="collectionName">
              <el-input v-model="form.collectionName"
                        placeholder="请输入收款人姓名"></el-input>
            </el-form-item>
            <el-form-item label="操作日期"
                          prop="operationDate">
              <el-date-picker v-model="form.operationDate"
                              type="date"
                              size="small"
                              value-format="yyyy-MM-dd"
                              format="yyyy-MM-dd"
                              placeholder="应收日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="操作人员"
                          prop="operationName">
              <el-input disabled
                        v-model="form.operationName"
                        placeholder="请输入操作人员"></el-input>
            </el-form-item>

            <el-form-item label="说明"
                          class="full"
                          prop="remarks">
              <el-input v-model="form.remarks"></el-input>
            </el-form-item>
          </div>
          <el-table :data="tableDataArr"
                    style="width: 100%">
            <el-table-column prop="chargeProjectName"
                             label="收款项目"
                             width="120"
                             align="center"></el-table-column>
            <!--<el-table-column prop="costMonth" label="费用月份" width="120"></el-table-column>-->
            <el-table-column prop="costPeriodStart"
                             label="费用期间"
                             width="260"
                             align="center"></el-table-column>
            <el-table-column prop="collectionAmount"
                             label="已收金额(元)"
                             width="120"
                             align="center"></el-table-column>
            <el-table-column prop="returnableAmount"
                             label="可退金额(元)"
                             width="120"
                             align="center"></el-table-column>
            <el-table-column prop="refundAmount"
                             label="退款金额(元)"
                             width="260"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.refundAmount"
                          placeholder="请输入"></el-input>
              </template>
            </el-table-column>

          </el-table>
        </el-form>

      </div>
      <span slot="foot">
        <el-button @click="close">取 消</el-button>
        <el-button @click="commit">提 交</el-button>
      </span>
    </v-dialog>
  </div>
</template>

<script>
import engineerList from '@/components/engineer-list'
import {
  addLessorRefund,
  getRefundAmountCount,
  getPayable,
} from '@/views/wy-finance/bill/api/actual'
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { mapState } from 'vuex'

export default {
  mixins: [BaseLoad],
  components: { engineerList },
  computed: {
    ...mapState({
      pay_status: (state) => {
        let data = state.dict.find((item) => item.type === 'pay_status') || {}
        let list = data.children || []
        return data.children || []
      },
      adjustment_type: (state) => {
        let data =
          state.dict.find((item) => item.type === 'adjustment_type') || {}
        let list = data.children || []
        return data.children || []
      },
    }),
  },
  data() {
    var validateBankAccount = (rule, value, callback) => {
      var bankAccount = value.replace(/\s/g, '')
      var num = /^\d*$/ //全数字
      if (!num.exec(bankAccount)) {
        callback('银行账号必须全为数字')
      }
      if (bankAccount.length < 16 || bankAccount.length > 19) {
        callback('银行账号长度必须在16到19之间')
      }
      //开头6位
      var strBin =
        '10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99'
      if (strBin.indexOf(bankAccount.substring(0, 2)) == -1) {
        callback('银行账号开头6位不符合规范')
      }
      var lastNum = value.substr(bankAccount.length - 1, 1) //取出最后一位（与luhn进行比较）

      var first15Num = value.substr(0, bankAccount.length - 1) //前15或18位
      var newArr = new Array()
      for (var i = first15Num.length - 1; i > -1; i--) {
        //前15或18位倒序存进数组
        newArr.push(first15Num.substr(i, 1))
      }
      var arrJiShu = new Array() //奇数位*2的积 <9
      var arrJiShu2 = new Array() //奇数位*2的积 >9

      var arrOuShu = new Array() //偶数位数组
      for (var j = 0; j < newArr.length; j++) {
        if ((j + 1) % 2 == 1) {
          //奇数位
          if (parseInt(newArr[j]) * 2 < 9)
            arrJiShu.push(parseInt(newArr[j]) * 2)
          else arrJiShu2.push(parseInt(newArr[j]) * 2)
        } //偶数位
        else arrOuShu.push(newArr[j])
      }

      var jishu_child1 = new Array() //奇数位*2 >9 的分割之后的数组个位数
      var jishu_child2 = new Array() //奇数位*2 >9 的分割之后的数组十位数
      for (var h = 0; h < arrJiShu2.length; h++) {
        jishu_child1.push(parseInt(arrJiShu2[h]) % 10)
        jishu_child2.push(parseInt(arrJiShu2[h]) / 10)
      }

      var sumJiShu = 0 //奇数位*2 < 9 的数组之和
      var sumOuShu = 0 //偶数位数组之和
      var sumJiShuChild1 = 0 //奇数位*2 >9 的分割之后的数组个位数之和
      var sumJiShuChild2 = 0 //奇数位*2 >9 的分割之后的数组十位数之和
      var sumTotal = 0
      for (var m = 0; m < arrJiShu.length; m++) {
        sumJiShu = sumJiShu + parseInt(arrJiShu[m])
      }

      for (var n = 0; n < arrOuShu.length; n++) {
        sumOuShu = sumOuShu + parseInt(arrOuShu[n])
      }

      for (var p = 0; p < jishu_child1.length; p++) {
        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p])
        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p])
      }
      //计算总和
      sumTotal =
        parseInt(sumJiShu) +
        parseInt(sumOuShu) +
        parseInt(sumJiShuChild1) +
        parseInt(sumJiShuChild2)

      //计算luhn值
      var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10
      var luhn = 10 - k

      if (lastNum == luhn) {
        callback()
      } else {
        callback('银行账号必需符合luhn规则')
      }
    }
    return {
      fileSize: 50,
      formData: {},
      input: '',
      value: '',
      area: [],
      form: {
        payStatus: '',
        adjustmentType: '',
        chargeProjectName: '',
        dataCode: '',
        lessorContractName: '',
        contractName: '',
        receivableMoney: '',
        customerName: '',
        costPeriodStart: '',
        costPeriodEnd: '',
        receivableDate: '',
        billNumber: '',
        taxAmount: '',
        remarks: '',
        paidType: '',
        costPeriodArr: [],
        refundBatch: '',
        bankName: '',
        bankAccount: '',
        collectionName: '',
        operationDate: '',
        operationName: '',
        refundAmount: '',
        actualId: '',
      },
      selectDataArr: [],
      dialogVisible: false,
      isEdit: false,
      rules: {
        // refundBatch: [{required: true, message: '请输入退款批复号', trigger: 'blur'}],
        bankName: [
          { required: true, message: '请输入收款银行', trigger: 'blur' },
        ],
        bankAccount: [
          { required: true, message: '请输入银行账号', trigger: 'blur' },
          { validator: validateBankAccount, trigger: 'blur' },
        ],
        collectionName: [
          { required: true, message: '请输入收款人姓名', trigger: 'blur' },
        ],
        operationDate: [
          { required: true, message: '请输入操作日期', trigger: 'blur' },
        ],
        // operationName: [{required: true, message: '请输入操作人员', trigger: 'blur'}],
      },
      tableDataArr: [
        {
          chargeProjectName: '',
          refundAmount: '',
          returnableAmount: '',
          collectionAmount: '',
          costPeriodStart: '',
          costPeriodArr: [],
        },
      ],
      contarct: '',
      approvalList: [],
      refundList: [],
    }
  },
  methods: {
    show(item) {
      this.dialogVisible = true
      setTimeout(() => {
        this.isEdit = false
        this.$refs.editForm.resetFields()
        if (item) {
          this.isEdit = true
          this.form = item
          this.form.operationName = item.createName
          Object.keys(this.form).forEach((key) => {
            this.form[key] = item[key]
          })
          this.tableDataArr[0].chargeProjectName = this.form.chargeProjectName
          this.tableDataArr[0].refundAmount = this.form.refundAmount
          this.tableDataArr[0].collectionAmount = this.form.collectionAmount
          // this.form.dataCode='SJBM'+this.getDateTime()
          /* this.form.bankName = null
                         this.form.bankAccount = null
                         this.form.collectionName = null*/
          /*var approval='TKPF'+this.getDate()
                        axios.all([getObjByApproval(Object.assign({'approval':approval})), getObj(item.rentContractId),getRefund(item.actualId)]).then(axios.spread((res1, res2,res3) => {
                            if(res1){
                                this.form.refundBatch=res1.data.msg
                                this.$forceUpdate()
                            }
                            if(res2){
                                this.contarct=res2.data.data
                            }
                            if(res3){
                                this.refundList=res3.data.data
                                this.refundList.map(refund=>{
                                    this.tableDataArr[0].returnableAmount-=refund.refundAmount
                                })
                            }
                        }))*/
          getRefundAmountCount(item.paymentId).then((res) => {
            if (res.data.code === 0) {
              this.tableDataArr[0].returnableAmount =
                this.tableDataArr[0].collectionAmount - res.data.data
            }
          })
          getObj(item.payableId).then((res) => {
            if (res.data.code === 0) {
              this.tableDataArr[0].costPeriodStart =
                res.data.data.costPeriodStart +
                '至' +
                res.data.data.costPeriodEnd
            }
          })
        }
        // console.log(this.form)
      }, 200)
    },
    commit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (
            this.tableDataArr[0].refundAmount === '' ||
            this.tableDataArr[0].refundAmount === undefined ||
            this.tableDataArr[0].refundAmount === null
          ) {
            this.$message.error('退款金额不能为空!')
          } else {
            if (
              this.tableDataArr[0].refundAmount >
              this.tableDataArr[0].returnableAmount
            ) {
              this.$message.error('退款金额不能大于可退金额!')
            } else {
              if (this.tableDataArr[0].refundAmount <= 0) {
                this.$message.error('退款金额不能小于或等于0!')
              } else {
                this.form.refundAmount = this.tableDataArr[0].refundAmount
                addLessorRefund(this.form).then((res) => {
                  if (res.data.code === 0) {
                    this.suc('添加成功')
                    this.dialogVisible = false
                    this.$emit('resetList')
                  } else {
                    this.err('添加失败')
                  }
                })
              }
            }
          }
        }
      })
    },
    beforeUpload() {
      this.loadAction('请稍等...')
    },
    selectionChange(val) {
      this.selectDataArr = val
    },
    /*getDateTime(){
                var date=new Date()
                return date.getFullYear()+((date.getMonth()+1)>=10?(date.getMonth()+1):'0'+(date.getMonth()+1))+(date.getDate()<10?'0'+date.getDate():date.getDate())
                    +(date.getHours()<10?'0'+date.getHours():date.getHours())+(date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes())+(date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds())
            },
            getDate(){
                var date=new Date()
                return date.getFullYear()+((date.getMonth()+1)>=10?(date.getMonth()+1):'0'+(date.getMonth()+1))+(date.getDate()<10?'0'+date.getDate():date.getDate())
            },*/
    close() {
      this.$emit('handleClose')
      this.dialogVisible = false
    },
    beforeClose(done) {
      this.$emit('beforeClose')
    },
  },
}
</script>

<style lang='scss' scoped>
@include formWrap(4);
@include data-title();

/deep/.el-date-editor.el-input {
  width: 253px;
}
</style>